//
//  NSString+Helper.m
//  02.用户登录&注册
//
//  Created by 刘凡 on 13-11-28.
//  Copyright (c) 2013年 itcast. All rights reserved.
//

#import "NSString+Helper.h"
#import<SystemConfiguration/CaptiveNetwork.h>
#import "AppDelegate.h"
#import "NSString+Password.h"

@implementation NSString (Helper)
+ (NSString *)replaceUnicode:(NSString *)unicodeStr {
    NSString *tempStr1 = [unicodeStr stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"];
    NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString* returnStr = [NSPropertyListSerialization propertyListWithData:tempData options:NSPropertyListImmutable format:NULL error:NULL];
    
    return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@"\n"];
}
+(NSString *)gethexBybin:(NSString *)BIN
{
    NSMutableDictionary  *hexDic = [[NSMutableDictionary alloc] init];
    
    hexDic = [[NSMutableDictionary alloc] initWithCapacity:16];
    
    [hexDic setObject:@"0" forKey:@"0000"];
    
    [hexDic setObject:@"1" forKey:@"0001"];
    
    [hexDic setObject:@"2" forKey:@"0010"];
    
    [hexDic setObject:@"3" forKey:@"0011"];
    
    [hexDic setObject:@"4" forKey:@"0100"];
    
    [hexDic setObject:@"5" forKey:@"0101"];
    
    [hexDic setObject:@"6" forKey:@"0110"];
    
    [hexDic setObject:@"7" forKey:@"0111"];
    
    [hexDic setObject:@"8" forKey:@"1000"];
    
    [hexDic setObject:@"9" forKey:@"1001"];
    
    [hexDic setObject:@"A" forKey:@"1010"];
    
    [hexDic setObject:@"B" forKey:@"1011"];
    
    [hexDic setObject:@"C" forKey:@"1100"];
    
    [hexDic setObject:@"D" forKey:@"1101"];
    
    [hexDic setObject:@"E" forKey:@"1110"];
    
    [hexDic setObject:@"F" forKey:@"1111"];
    
    NSString *HEXString=[NSString string];
    
    for (int i=0; i<[BIN length]; i=i+4) {
        
        NSRange rage;
        
        rage.length = 4;
        
        rage.location = i;
        
        NSString *key = [BIN substringWithRange:rage];
        
        //NSLog(@"%@",[NSString stringWithFormat:@"%@",[hexDic objectForKey:key]]);
        
        HEXString = [NSString stringWithFormat:@"%@%@",HEXString,[NSString stringWithFormat:@"%@",[hexDic objectForKey:key]]];
        
    }
    
    //NSLog(@"转化后的二进制为:%@",binaryString);
    
    return HEXString;
    
}
+(NSString *)getBinaryByhex:(NSString *)hex withlength:(NSUInteger)length
{
    NSMutableDictionary  *hexDic = [[NSMutableDictionary alloc] init];
    
    hexDic = [[NSMutableDictionary alloc] initWithCapacity:16];
    
    [hexDic setObject:@"0000" forKey:@"0"];
    
    [hexDic setObject:@"0001" forKey:@"1"];
    
    [hexDic setObject:@"0010" forKey:@"2"];
    
    [hexDic setObject:@"0011" forKey:@"3"];
    
    [hexDic setObject:@"0100" forKey:@"4"];
    
    [hexDic setObject:@"0101" forKey:@"5"];
    
    [hexDic setObject:@"0110" forKey:@"6"];
    
    [hexDic setObject:@"0111" forKey:@"7"];
    
    [hexDic setObject:@"1000" forKey:@"8"];
    
    [hexDic setObject:@"1001" forKey:@"9"];
    
    [hexDic setObject:@"1010" forKey:@"A"];
    
    [hexDic setObject:@"1011" forKey:@"B"];
    
    [hexDic setObject:@"1100" forKey:@"C"];
    
    [hexDic setObject:@"1101" forKey:@"D"];
    
    [hexDic setObject:@"1110" forKey:@"E"];
    
    [hexDic setObject:@"1111" forKey:@"F"];
    
    NSString *binaryString=[NSString string];
    
    for (int i=0; i<[hex length]; i++) {
        
        NSRange rage;
        
        rage.length = 1;
        
        rage.location = i;
        
        NSString *key = [[hex uppercaseString] substringWithRange:rage];
        
        //NSLog(@"%@",[NSString stringWithFormat:@"%@",[hexDic objectForKey:key]]);
        
        binaryString = [NSString stringWithFormat:@"%@%@",binaryString,[NSString stringWithFormat:@"%@",[hexDic objectForKey:key]]];
        
    }
    
    //NSLog(@"转化后的二进制为:%@",binaryString);
    
    if (binaryString.length<length) {
        NSUInteger j=binaryString.length;
        for (NSUInteger i=0; i<length-j; i++) {
            binaryString=[NSString stringWithFormat:@"0%@",binaryString];
           // [binaryString insertString:@"0" atIndex:0];
        }
    }else
    {
        binaryString=[binaryString substringFromIndex:binaryString.length-length];
    }
    return binaryString;
    
}

- (NSString *)stringFromHexString { //
    NSString *hexString=self;
    char *myBuffer = (char *)malloc((int)[hexString length] / 2 + 1);
    bzero(myBuffer, [hexString length] / 2 + 1);
    for (int i = 0; i < [hexString length] - 1; i += 2) {
        unsigned int anInt;
        NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];
        NSScanner * scanner = [[NSScanner alloc] initWithString:hexCharStr];
        [scanner scanHexInt:&anInt];
        myBuffer[i / 2] = (char)anInt;
    }
    NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:4];
//    NSLog(@"------字符串=======%@",unicodeString);
    return unicodeString;
    
    
}
+ (NSString *)convertDataToHexStr:(NSData *)data {
    if (!data || [data length] == 0) {
        return @"";
    }
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];
    
    return string;
}
+(NSData *)convertHexStrToData:(NSString *)str {
    if (!str || [str length] == 0) {
        return nil;
    }
    
    NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:8];
    NSRange range;
    if ([str length] % 2 == 0) {
        range = NSMakeRange(0, 2);
    } else {
        range = NSMakeRange(0, 1);
    }
    for (NSInteger i = range.location; i < [str length]; i += 2) {
        unsigned int anInt;
        NSString *hexCharStr = [str substringWithRange:range];
        NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];
        
        [scanner scanHexInt:&anInt];
        NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];
        [hexData appendData:entity];
        
        range.location += range.length;
        range.length = 2;
    }
    
    NSLog(@"hexdata: %@", hexData);
    return hexData;
}
+ (NSString *)hexStringFromString:(NSString *)string{
    NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];
    Byte *bytes = (Byte *)[myD bytes];
    //下面是Byte 转换为16进制。
    NSString *hexStr=@"";
    for(int i=0;i<[myD length];i++)
        
    {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        
        if([newHexStr length]==1)
            
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        
        else
            
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr]; 
    } 
    return hexStr; 
}
-(NSInteger )intFromHexString { //
    NSString *hexString=self;
    NSInteger hexint=0;
for (int i = 0; i < [hexString length] - 1; i += 2) {
           unsigned int anInt;
        NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];
        NSScanner * scanner = [[NSScanner alloc] initWithString:hexCharStr];
        [scanner scanHexInt:&anInt];
    hexint=hexint+anInt;
}
  //  NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:4];
    //NSLog(@"------字符串=======%@",unicodeString);
    return hexint;
    
    
}
#pragma mark 清空字符串中的空白字符
- (NSString *)trimString
{
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
-(NSString *)token
{
    NSString *token = [self stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    NSString *deviceToken = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    
   // NSLog(@"deviceToken:%@", deviceToken);
    return deviceToken;
}
#pragma mark 是否空字符串
- (BOOL)isEmptyString
{
    return (self == nil || self.length == 0);
}

#pragma mark 返回沙盒中的文件路径
- (NSString *)documentsPath
{
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    return [path stringByAppendingString:self];
}

#pragma mark 写入系统偏好
- (void)saveToNSDefaultsWithKey:(NSString *)key
{
    [[NSUserDefaults standardUserDefaults] setObject:self forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
#pragma mark 获取网络
+(NSString *)getNetWorkStates{
    UIApplication *app = [UIApplication sharedApplication];
    NSArray *children = [[[app valueForKeyPath:@"statusBar"]valueForKeyPath:@"foregroundView"]subviews];
    NSString *state = [[NSString alloc]init];
    int netType = 0;
    //获取到网络返回码
    for (id child in children) {
        if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
            //获取到状态栏
            netType = [[child valueForKeyPath:@"dataNetworkType"]intValue];
            
            switch (netType) {
                case 0:
                    state = @"无网络";
                    //无网模式
                    break;
                case 1:
                    state = @"2G";
                    break;
                case 2:
                    state = @"3G";
                    break;
                case 3:
                    state = @"4G";
                    break;
                case 5:
                {
                    state = @"WIFI";
                }
                    break;
                default:
                    break;
            }
        }
    }
    //根据状态选择
    return state;
}
+(NSString *) getDeviceSSID

{
    
    NSArray *ifs = CFBridgingRelease(CNCopySupportedInterfaces());
    
    
    
    id info = nil;
    
    for (NSString *ifnam in ifs) {
        
        info = CFBridgingRelease(CNCopyCurrentNetworkInfo(( CFStringRef)CFBridgingRetain(ifnam)));
        
        if (info && [info count]) {
            
            break;
            
        }
        
    }
    
    NSDictionary *dctySSID = (NSDictionary *)info;
    
    NSString *ssid = [dctySSID objectForKey:@"SSID"] ;
    
  
    
    return ssid;
    
}
+(NSString *)getSign:(NSDictionary *)parmars{
    NSArray *keyary=[parmars allKeys];
    NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES];
    NSArray *descriptors = [NSArray arrayWithObject:descriptor];
    NSArray *keyarysort=[keyary sortedArrayUsingDescriptors:descriptors];
    NSMutableString *sign=[NSMutableString string];
    for (NSUInteger i=0; i<keyarysort.count; i++) {
        if ([parmars[keyarysort[i]]length] != 0) {
            [sign appendString:[NSString stringWithFormat:@"%@=%@&",keyarysort[i],parmars[keyarysort[i]]]];
        }
    }
    [sign appendString:[NSString stringWithFormat:@"key=%@",DTCloudKitAppKey]];
    return [sign MD5];
}
- (BOOL)isMobileNumber
{
    
    NSString * phoneRegex = @"^[1][34578][0-9]{9}$";
    NSPredicate *pre=[NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    BOOL isMatch = [pre evaluateWithObject:self];
    return isMatch;
}

- (BOOL)isRegexPassword
{
    NSString * phoneRegex = @"^[0-9a-zA-Z_@.]{6,20}";
    NSPredicate *pre=[NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    BOOL isMatch = [pre evaluateWithObject:self];
    return isMatch;
    
}

+ (NSString *)getCurrentTime:(NSString *)dateFormat
{
    NSDate *currentDate = [NSDate date]; //获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    if (dateFormat) {
        [dateFormatter setDateFormat:dateFormat];
    } else {
        [dateFormatter setDateFormat:@"YYYY/MM/dd HH:mm:ss SS"];
    }
    NSString *dateString = [dateFormatter stringFromDate:currentDate];
    NSLog(@"dateString:%@",dateString);
    
    return dateString;
}

+ (NSString *)getTimeWithTimestamp:(NSString *)stamp format:(NSString *)dateFormat
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSDate * date = [NSDate dateWithTimeIntervalSince1970:[stamp longLongValue]];
    if (dateFormat) {
        [dateFormatter setDateFormat:dateFormat];
    } else {
        [dateFormatter setDateFormat:@"YYYY/MM/dd HH:mm:ss SS"];
    }
    NSString *dateString = [dateFormatter stringFromDate:date];
    NSLog(@"dateString:%@",dateString);
    
    return dateString;
}


+ (NSString *)convertDataToHexStr:(NSData *)data  andismac:(BOOL)mac{
    if (!data || [data length] == 0) {
        return @"";
    }
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr;
            if (i==byteRange.length-1||mac==NO) {
                hexStr = [NSString stringWithFormat:@"%02X", (dataBytes[i]) & 0xff];
            }else{
                
                hexStr = [NSString stringWithFormat:@"%02X:", (dataBytes[i]) & 0xff];
            }
            [string appendString:hexStr];
            //            if ([hexStr length] == 2) {
            //                [string appendString:hexStr];
            //            } else {
            //                [string appendFormat:@"0%@", hexStr];
            //            }
        }
    }];
    
    return string;
}

+ (NSString *)timeFromHexString:(NSString *)hexString
{
    NSInteger year = [[hexString substringWithRange:NSMakeRange(0, 2)] intFromHexString]*256 + [[hexString substringWithRange:NSMakeRange(2, 2)] intFromHexString];
    NSInteger month = [[hexString substringWithRange:NSMakeRange(4, 2)] intFromHexString];
    NSInteger day = [[hexString substringWithRange:NSMakeRange(6, 2)] intFromHexString];
    
    NSString * Month = month<10? [NSString stringWithFormat:@"0%ld",(long)month] : [NSString stringWithFormat:@"%ld",(long)month] ;
    NSString * Day   = day  <10? [NSString stringWithFormat:@"0%ld",(long)day]   : [NSString stringWithFormat:@"%ld", (long)day];
    
    NSString * timeString = [NSString stringWithFormat:@"%ld%@%@",(long)year,Month,Day];
    return timeString;
}

+ (BOOL)isContainsTwoEmoji:(NSString *)string
{
    __block BOOL isEomji = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
     ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         const unichar hs = [substring characterAtIndex:0];
         //         NSLog(@"hs++++++++%04x",hs);
         if (0xd800 <= hs && hs <= 0xdbff) {
             if (substring.length > 1) {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc && uc <= 0x1f77f)
                 {
                     isEomji = YES;
                 }
                 //                 NSLog(@"uc++++++++%04x",uc);
             }
         } else if (substring.length > 1) {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3|| ls ==0xfe0f) {
                 isEomji = YES;
             }
             //             NSLog(@"ls++++++++%04x",ls);
         } else {
             if (0x2100 <= hs && hs <= 0x27ff && hs != 0x263b) {
                 isEomji = YES;
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 isEomji = YES;
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 isEomji = YES;
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 isEomji = YES;
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50|| hs == 0x231a ) {
                 isEomji = YES;
             }
         }
         
     }];
    return isEomji;
}

- (BOOL)isNumberString
{
    for (int i = 0; i < self.length; i++) {
        int acII = [[self substringWithRange:NSMakeRange(i, 1)] characterAtIndex:0];
        if (!(acII >= 48 && acII <= 57)){
            return NO;
        }
    }
    return YES;
}
@end
